import { Button, Dialog, Form } from '@alifd/next';
import { t } from '@lingui/macro';
import React, { useRef, useState, useEffect } from 'react';
import DrawerFooter from '@/components/DrawerFooter';
import { observable } from 'mobx';
import TauSimpleSelect from '@/components/TauSimpleSelect';
import { observer } from 'mobx-react-lite';
import { useStore } from '@/hooks';

const RelevancyActivity = ({ coupon, visible, onClose, onSubmit }) => {
  const [formData] = useState(() => observable({}));
  const editCtx = useRef({ origin: {}, changed: {} }).current;
  const { couponStore: store } = useStore();

  useEffect(() => {
    _.assign(formData, coupon);
    return (() => {
      _.set(formData, 'activityId', '');
    });
  }, [visible]);

  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(formData, name, value);

    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleSubmit = (__, errors, ___) => {
    if (!_.isEmpty(errors)) {
      console.log('🚀 _ file: RelevancyActivity.jsx:31 _ errors:', errors);
      return;
    }
    onSubmit?.(formData);
  };

  return (
    <Dialog
      v2
      visible={visible}
      title={t`关联活动`}
      onClose={onClose}
      closeMode={['esc', 'mask', 'close']}
      width={'450px'}
    >
      <Form
        inline
        value={formData}
        onChange={handleChange}
      >
        <Form.Item
          label={t`活动名称`}
          labelAlign="top"
          required
          name="activityId"
          useLabelForErrorMessage
        >
          <TauSimpleSelect style={{ width: '20vw' }} data={store.activitys} />
        </Form.Item>
        <DrawerFooter>
          <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>
          <Button style={{ marginLeft: 8 }} onClick={onClose}>{t`取消`}</Button>
        </DrawerFooter>
      </Form>
    </Dialog>
  );
};

export default observer(RelevancyActivity);
